import { useTableScroll } from '@/hooks/useTableScroll';
import { getTallyBookRecord } from '@/services/financial-center';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { Button, Radio } from 'antd';
import { FormInstance } from 'antd/lib';
import { useRef, useState } from 'react';
import { useAntdColumnResize } from 'react-antd-column-resize';

const statusEnum = {
  '': { text: '不限' },
  WAIT_PAY: { text: '待支付' },
  SUCCESS: { text: '充值成功' },
  CLOSED: { text: '已关闭' },
} as any;

const RechargeRecord = () => {
  const [count] = useState(0);
  const tableScrollHeight = useTableScroll({}, count);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [mainTableParams, setMainTableParams] = useState({});

  const columns: ProColumns<any>[] = [
    {
      title: '转账状态',
      dataIndex: 'status',
      valueType: 'radioButton',
      renderFormItem: () => {
        return (
          <Radio.Group buttonStyle="solid" defaultValue={''}>
            <Radio.Button value={''}>不限</Radio.Button>
            <Radio.Button value={'WAIT_PAY'}>待支付</Radio.Button>
            <Radio.Button value={'SUCCESS'}>充值成功</Radio.Button>
            <Radio.Button value={'CLOSED'}>已关闭</Radio.Button>
          </Radio.Group>
        );
      },
      hideInTable: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 160,
      valueType: 'dateRange',
      order: -1,
      formItemProps: {
        label: '批次创建时间',
      },
      render: (_, record) => {
        return <div>{record.createTime}</div>;
      },
      search: {
        transform: (value: any) => {
          if (!value) return null;
          return {
            minCreateTime: value[0],
            maxCreateTime: value[1],
          };
        },
      },
    },
    {
      title: '入金方式',
      dataIndex: 'source',
      width: 160,
      hideInSearch: true,
      valueEnum: {
        AUTO: { text: '支付宝余额转入' },
        LARGE_DEPOSIT: { text: '汇款充值' },
      },
    },
    {
      title: '收款方支付宝账号',
      dataIndex: 'alipayNickName',
      width: 180,
      formItemProps: {
        label: '支付宝账号',
      },
    },
    {
      title: '来账方汇款账号',
      dataIndex: 'payerIdentity',
      width: 180,
      hideInSearch: true,
      render: (_, record) => {
        return (
          <div>
            {record.payerIdentity
              ? `${record.payerIdentity}${record.payerName}`
              : record.alipayNickName}
          </div>
        );
      },
    },
    {
      title: '支付编号',
      dataIndex: 'id',
      width: 180,
      hideInSearch: true,
    },
    {
      title: '外部订单号',
      dataIndex: 'importBizNo',
      width: 180,
    },
    {
      title: '充值金额',
      dataIndex: 'transAmount',
      width: 160,
      render: (_, record) => {
        return <div>¥{record.transAmount}</div>;
      },
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 160,
      render: (_, record) => {
        return (
          <div
            className={`${record.status === 'SUCCESS' ? 'text-[#00bdff]' : ''}`}
          >
            {statusEnum[record.status].text}
          </div>
        );
      },
      hideInSearch: true,
    },
    {
      title: '完成时间',
      dataIndex: 'endTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      hideInSearch: true,
      dataIndex: 'option',
      fixed: 'right',
      width: 100,
      render: (_, record) => {
        if (record.status === 'WAIT_PAY') {
          return (
            <div>
              <span
                className="text-[#00bdff] cursor-pointer"
                onClick={() => {
                  window.open(record.payUrl);
                }}
              >
                去付款
              </span>
            </div>
          );
        }
      },
    },
  ];
  const { resizableColumns, components, tableWidth } =
    // @ts-ignore
    useAntdColumnResize(() => {
      return { columns };
    }, []);
  return (
    <div>
      <ProTable
        scroll={{ y: tableScrollHeight, x: tableWidth }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        formRef={formRef}
        form={{
          onValuesChange: (changedValues) => {
            if (Object.keys(changedValues).includes('status')) {
              formRef?.current?.submit();
            }
          },
        }}
        dateFormatter="YYYY-MM-DD 00:00:00"
        request={async (params: any) => {
          const { current, ...rest } = params;
          const searchData = {
            pageNo: current - 1,
            ...rest,
          };
          try {
            const { data, count, success } = (await getTallyBookRecord(
              searchData,
            )) as any;
            setMainTableParams(searchData);
            if (success) {
              return {
                data,
                total: count,
                success,
              };
            }
            return {
              data: [],
              total: count,
              success: true,
            };
          } catch (error) {
            return {
              data: [],
              success: false,
            };
          }
        }}
        components={components}
        columns={resizableColumns as ProColumns[]}
        pagination={{
          defaultPageSize: 20,
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        actionRef={actionRef}
        cardBordered
        columnsState={{
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
        }}
        toolBarRender={() => [
          <Button
            key="button"
            type="primary"
            onClick={() => {
              const formDom = document.createElement('form');
              formDom.setAttribute('type', 'hidden');
              formDom.setAttribute('target', '_black');
              formDom.setAttribute('method', 'get');
              formDom.setAttribute(
                'action',
                '/api/merchant/safe-pay-book-account-order/export',
              );
              const inputDom = document.createElement('input');
              inputDom.setAttribute('type', 'hidden');
              inputDom.setAttribute('name', 'searchModelJson');

              inputDom.setAttribute('value', JSON.stringify(mainTableParams));

              formDom.append(inputDom);
              document.body.append(formDom);
              formDom.submit();
            }}
          >
            导出
          </Button>,
        ]}
      />
    </div>
  );
};

export default RechargeRecord;
